# 股票复盘系统主程序
import sys
from datetime import datetime, timedelta
import pandas as pd
import json

# 导入自定义模块
from modules.data_collector import DataCollector
from modules.analyzer import Analyzer
from modules.predictor import Predictor
from modules.report_generator import ReportGenerator
from config import DATA_PATH

# 初始化各模块
data_collector = DataCollector()
analyzer = Analyzer()
predictor = Predictor()
report_generator = ReportGenerator()

def analyze_stock(stock_code):
    """分析股票"""
    try:
        # 设置日期范围（过去一个月）
        end_date = datetime.now().strftime('%Y-%m-%d')
        start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
        
        # 获取股票基本信息
        stock_info = data_collector.get_stock_basic(stock_code)
        if isinstance(stock_info, dict) and 'error' in stock_info:
            print(f'错误: {stock_info["error"]}')
            return
        
        if not stock_info:
            print(f'错误: 未找到股票代码 {stock_code} 的信息')
            return
        
        stock_name = stock_info['name']
        print(f'\n开始分析 {stock_code} {stock_name} 从 {start_date} 到 {end_date} 的数据...')
        
        # 获取股票日K线数据
        daily_data = data_collector.get_daily_data(stock_code, start_date, end_date)
        if daily_data.empty:
            print(f'错误: 未找到股票代码 {stock_code} 的交易数据')
            return
        
        # 获取大盘指数数据（默认上证指数）
        index_data = data_collector.get_index_data('000001.SH', start_date, end_date)
        
        # 获取资金流向数据
        money_flow_data = data_collector.get_money_flow(stock_code, start_date, end_date)
        
        # 获取相关新闻
        news_data = data_collector.get_news(stock_code)
        
        # 计算技术指标
        daily_data = analyzer.calculate_technical_indicators(daily_data)
        
        # 分析价格趋势
        price_analysis = analyzer.analyze_price_trend(daily_data)
        
        # 分析成交量
        volume_analysis = analyzer.analyze_volume(daily_data)
        
        # 分析技术指标
        tech_analysis = analyzer.analyze_technical_indicators(daily_data)
        
        # 与大盘对比
        market_comparison = analyzer.compare_with_market(daily_data, index_data)
        
        # 分析资金流向
        money_flow_analysis = analyzer.analyze_money_flow(money_flow_data)
        
        # 生成复盘报告
        report = report_generator.generate_report(
            stock_code, stock_name, daily_data, index_data, money_flow_data, news_data,
            price_analysis, volume_analysis, tech_analysis, market_comparison, money_flow_analysis
        )
        
        # 保存报告到本地
        report_file = f"{stock_code}_report.json"
        report_generator.save_report(report, report_file)
        
        # 在控制台打印报告
        print('\n=== 复盘分析报告 ===')
        print(f'股票: {stock_code} {stock_name}')
        print(f'分析日期: {start_date} 至 {end_date}')
        print('\n1. 价格趋势分析')
        print(price_analysis)
        print('\n2. 成交量分析')
        print(volume_analysis)
        print('\n3. 技术指标分析')
        print(tech_analysis)
        print('\n4. 市场对比分析')
        print(market_comparison)
        print('\n5. 资金流向分析')
        print(money_flow_analysis)
        print('\n6. 相关新闻')
        for news in news_data[:5]:  # 只显示最新的5条新闻
            print(f"- {news['date']}: {news['title']}")
        
        print(f'\n详细报告已保存至: {report_file}')
        
    except Exception as e:
        print(f'分析过程中出错: {str(e)}')

def main():
    if len(sys.argv) != 2:
        print('使用方法: python app.py <股票代码>')
        print('示例: python app.py 000001')
        sys.exit(1)
    
    stock_code = sys.argv[1]
    analyze_stock(stock_code)

if __name__ == '__main__':
    main()